<?php
/**
 * @author Radovan Dvorsky
 * @version 20100326
 */
require_once ('application/default/models/Db/Mapper/MapperAbstract.php');

class Db_Mapper_Commission extends Db_Mapper_Abstract {
		
	/** 
	 * @param Db_Model_Commission $commission
	 */
	public function save(Db_Model_Abstract $commission,$forceInsert = false){
		
		if(!$commission instanceof Db_Model_Commission){
			throw new Exception('$commission is not instance of Db_Model_Commission');
		}	
		
		try{
			
			$adapter = $this->getTable()->getAdapter();
			$adapter->beginTransaction();
			
			$commissionData = array(
				'name' => $commission->getName()
			);
			
			$cid = $this->getTable()->insert($commissionData);
			
			$profCommMapper = new Db_Mapper_ProfessorCommission();
			
			if(count($commission->getProfessors() > 0)){
				foreach($commission->getProfessors() as $professor){
					$profCommMapper->save(
						new Db_Model_ProfessorCommission(array(
							'pid' => $professor->getPid(),
							'cid' => $cid
							)
						),
						true
					);	
				}
			}
			
			$adapter->commit();	
			
		} catch (Zend_Exception $e){
			$adapter->rollBack();
			throw new Db_Exception($e->getMessage());
		}
	}	
	
	
	/**
	 * Odstrani profesora z komisie
	 * 
	 * @param Db_Model_Professor $professor
	 * 
	 * @return int Pocet odstranenych riadkov
	 */
	public function removeProfessor(Db_Model_Professor $professor){
		
		if(!$professor instanceof Db_Model_Professor){
			throw new Exception('$professor is not instance of Db_Model_Professor');
		}
		
		$where = $this->getTable()->getAdapter()->quoteInto('pid = ?',$professor->getPid(),Zend_Db::INT_TYPE);
		
		$row = $this->getTable()->fetchRow($where);
		
		return $row->delete();	
	}
	
	
	/**
	 * Prida profesora do komisie
	 * 
	 * @param Db_Model_Professor $professor
	 * @param Db_Model_Commission $commission
	 * 
	 * @return mixed Posledny vlozeny primarny kluc 
	 */
	public function addProfessor(Db_Model_Professor $professor,Db_Model_Commission $commission){
		
		if(!$professor instanceof Db_Model_Professor){
			throw new Exception('$professor is not instance of Db_Model_Professor');
		}
		
		if(!$commission instanceof Db_Model_Commission){
			throw new Exception('$commission is not instance of Db_Model_Commission');
		}
		
		$professorCommissionMapper = new Db_Mapper_ProfessorCommission();
		$professorCommissionModel = new Db_Model_ProfessorCommission(array(
			'pid' => $professor->getPid(),
			'cid' => $commission->getCid()
			)
		);
		
		return $newRow = $professorCommissionMapper->save($professorCommissionModel,true);		
	}
}

?>